package com.wwj.auction.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.wwj.auction.common.entity.ot.Shop;
import com.wwj.auction.common.entity.ot.UserInfo;
import com.wwj.auction.common.entity.to.CreateOrderTo;
import com.wwj.auction.common.enums.PayTypeEnum;
import com.wwj.auction.order.client.ServiceAdminClient;
import com.wwj.auction.order.client.ServiceLoginClient;
import com.wwj.auction.order.entity.ShopOrder;
import com.wwj.auction.order.entity.Store;
import com.wwj.auction.order.entity.vo.OrderVo;
import com.wwj.auction.order.entity.vo.SimpleOrderVo;
import com.wwj.auction.order.mapper.OrderMapper;
import com.wwj.auction.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wwj
 * @since 2021-08-30
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, ShopOrder> implements OrderService {

    @Autowired
    private ServiceAdminClient serviceAdminClient;
    @Autowired
    private ServiceLoginClient serviceLoginClient;

    @Override
    public int create(CreateOrderTo createOrderTo) {
        UserInfo userInfo = createOrderTo.getUserInfo();
        Shop shop = createOrderTo.getShop();
        // 若当前商品的订单已经存在，则无需生成
        ShopOrder order = baseMapper.selectOne(
                Wrappers.lambdaQuery(ShopOrder.class)
                        .eq(ShopOrder::getShopId, shop.getId()));
        System.out.println(shop);
        System.out.println(order);
        if (order == null) {
            // 封装数据
            order = new ShopOrder();
            order.setAddress(userInfo.getDetailAddress());
            // TODO 付款方式暂时均设为在线付款
            order.setPayType(PayTypeEnum.PAY_ON_ONLINE.getStatus());
            order.setShopIndexImage(shop.getShopIndexImage());
            order.setShopName(shop.getShopName());
            // 远程查询当前用户的最高出价
            LinkedHashMap map = (LinkedHashMap) serviceLoginClient.first(createOrderTo.getShop().getId()).getData().get("userInfo");
            Double offerPrice = (Double) map.get("offerPrice");
            order.setShopPrice(new BigDecimal(offerPrice));
            order.setShopFreight(shop.getShopFreight());
            order.setName(userInfo.getNickName());
            order.setPhone(userInfo.getPhone());
            order.setEarnestMoney(shop.getEarnestMoney());
            // 随机一个订单号
            String orderNo = UUID.randomUUID().toString().replaceAll("-", "");
            order.setOrderNo(orderNo);
            order.setUserId(userInfo.getId());
            order.setShopId(shop.getId());
            // 创建时间
            order.setCreateTime(LocalDateTime.now());
            // 保存
            return baseMapper.insert(order);
        } else {
            return 0;
        }
    }

    @Override
    public OrderVo get(Integer shopId) {
        // 根据商品id查询订单信息
        ShopOrder shopOrder = baseMapper.selectOne(
                Wrappers.lambdaQuery(ShopOrder.class)
                        .eq(ShopOrder::getShopId, shopId));
        // 封装Vo数据
        OrderVo orderVo = new OrderVo();
        orderVo.setBuyerName(shopOrder.getName());
        orderVo.setPhone(shopOrder.getPhone());
        orderVo.setBuyerAddress(shopOrder.getAddress());
        orderVo.setShopName(shopOrder.getShopName());
        orderVo.setShopPrice(shopOrder.getShopPrice().toString());
        orderVo.setShopIndexImage(shopOrder.getShopIndexImage());
        orderVo.setShopFreight(shopOrder.getShopFreight().toString());
        orderVo.setOrderNo(shopOrder.getOrderNo());
        // 查询店铺名
        LinkedHashMap<String, Object> storeData = (LinkedHashMap<String, Object>) serviceAdminClient.getStoreName(shopId).getData();
        // 先将LinkedHashMap转为json
        String storeJson = JSONObject.toJSONString(storeData);
        // 再将json转回实体
        Store store = JSONObject.parseObject(storeJson, Store.class);
        // TODO 远程查询商品所属的店铺名为NULL，待解决
        orderVo.setStoreName(store.getStoreName());
        return orderVo;
    }

    @Override
    public List<Integer> getIdByOrderNo(String orderNo) {
        List<Integer> ids = new ArrayList<>();
        ShopOrder shopOrder = baseMapper.selectOne(
                Wrappers.lambdaQuery(ShopOrder.class)
                        .eq(ShopOrder::getOrderNo, orderNo));
        ids.add(shopOrder.getUserId());
        ids.add(shopOrder.getShopId());
        return ids;
    }

    @Override
    public Map<String, String> getVolumeAndAmount() {
        Map<String, String> map = Maps.newHashMap();
        List<ShopOrder> shopOrderList = baseMapper.selectList(null);
        // 计算交易额
        Optional<BigDecimal> optional = shopOrderList.stream().map(shopOrder -> {
            return shopOrder.getShopPrice();
        }).reduce(BigDecimal::add);

        map.put("volume", String.valueOf(shopOrderList.size()));
        map.put("transactionAmount", optional.get().toString());
        return map;
    }

    @Override
    public List<BigDecimal> getAmount() {
        BigDecimal january = new BigDecimal(0);
        BigDecimal february = new BigDecimal(0);
        BigDecimal march = new BigDecimal(0);
        BigDecimal april = new BigDecimal(0);
        BigDecimal may = new BigDecimal(0);
        BigDecimal june = new BigDecimal(0);
        BigDecimal july = new BigDecimal(0);
        BigDecimal august = new BigDecimal(0);
        BigDecimal september = new BigDecimal(0);
        BigDecimal october = new BigDecimal(0);
        BigDecimal november = new BigDecimal(0);
        BigDecimal december = new BigDecimal(0);

        List<ShopOrder> shopOrderList = baseMapper.selectList(null);
        // 统计每个月份的交易额
        for (ShopOrder shopOrder : shopOrderList) {
            LocalDateTime createTime = shopOrder.getCreateTime();
            int month = createTime.getMonth().getValue();
            switch (month) {
                case 1:
                    january = january.add(shopOrder.getShopPrice());
                    break;
                case 2:
                    february = february.add(shopOrder.getShopPrice());
                    break;
                case 3:
                    march = march.add(shopOrder.getShopPrice());
                    break;
                case 4:
                    april = april.add(shopOrder.getShopPrice());
                    break;
                case 5:
                    may = may.add(shopOrder.getShopPrice());
                    break;
                case 6:
                    june = june.add(shopOrder.getShopPrice());
                    break;
                case 7:
                    july = july.add(shopOrder.getShopPrice());
                    break;
                case 8:
                    august = august.add(shopOrder.getShopPrice());
                    break;
                case 9:
                    september = september.add(shopOrder.getShopPrice());
                    break;
                case 10:
                    october = october.add(shopOrder.getShopPrice());
                    break;
                case 11:
                    november = november.add(shopOrder.getShopPrice());
                    break;
                case 12:
                    december = december.add(shopOrder.getShopPrice());
                    break;
                default:
                    break;
            }
        }
        List<BigDecimal> list = new ArrayList<>();
        list.add(january);
        list.add(february);
        list.add(march);
        list.add(april);
        list.add(may);
        list.add(june);
        list.add(july);
        list.add(august);
        list.add(september);
        list.add(october);
        list.add(november);
        list.add(december);
        return list;
    }

    @Override
    public List<SimpleOrderVo> getOrderList() {
        List<ShopOrder> shopOrderList = baseMapper.selectList(null);
        List<SimpleOrderVo> simpleOrderVoList = shopOrderList.stream().map(shopOrder -> {
            SimpleOrderVo simpleOrderVo = new SimpleOrderVo();
            simpleOrderVo.setOrderNo(shopOrder.getOrderNo());
            simpleOrderVo.setShopPrice(shopOrder.getShopPrice().toString());
            simpleOrderVo.setPayType(shopOrder.getPayType() == 0 ? "货到付款" : "在线付款");
            return simpleOrderVo;
        }).collect(Collectors.toList());
        return simpleOrderVoList;
    }

    @Override
    public ShopOrder getOrder(String orderNo) {
        return baseMapper.selectOne(
                Wrappers.lambdaQuery(ShopOrder.class)
                        .eq(ShopOrder::getOrderNo, orderNo));
    }
}
